<?php if(!defined('OCTOMS')){header('HTTP/1.1 403');die('{"error":"forbidden"}');}
/*
 * @package       OctoMS.com
 * @subpackage    DesignJotter
 * @link          http://designjotter.com
 * @copyright     Copyright 2012, Valentino-Jivko Radosavlevici
 * @license       GPL v3.0 (http://www.gnu.org/licenses/gpl-3.0.txt)
 * 
 * Redistributions of files must retain the above copyright notice.
 * 
 * @since         OctoMS 0.0.1
 */
	
	/*
	 * Lighthouse class
	 * 
	 * 
	 * 
	 * @package OctoMS
	 * @subpackage test
	 * @version 0.1
	 * 
	 * @author Valentino-Jivko Radosavlevici
	 */
	class lighthouse extends octoms
	{
		/**
		 * Available actions
		 */
		var $actions = array();
		
		/**
		 * Get available methods
		 */
		var $methods = array();
		
		/**
		 * Current action
		 */
		var $current_action;
		
		/**
		 * Current method
		 */
		var $current_method;
		
		/**
		 * The object of the dispatched controller
		 */
		var $object;
		
		/**
		 * The current theme name
		 */
		var $theme;
		
		/**
		 * Constructor - Load libraries, helpers and models here, preferably
		 * 
		 * @package OctoMS.com
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function __construct()
		{
			// Start the session
			$this->_('session')->start();
			
		}// end function __construct()
		
		/**
		 * Preproccessor
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function _pre()
		{
			// Default configurations
			$this->template->_conf('method',$this->current_method)->_conf('page','index');
			
			// Load the common JS
			wp_enqueue_script('jquery',get_template_directory_uri().'/core/wizard/views/js/common/jquery.js',false,'1.0');
			wp_enqueue_script('jquery-ui',get_template_directory_uri().'/core/wizard/views/js/common/jquery-ui.js',false,'1.0');
			
			// Load the WP-OctoMS JavaScript Library
			$this->template->infooter = false;
			$this->template->js('wp-octoms')->css('wp-octoms');
			$this->template->infooter = true;
			
			// Create the menu
			$menu = array();
			foreach ($this->actions AS $k => $v)
			{
				if ($v == $this->current_action)
				{
					$methods = array();
					foreach ($this->methods AS $_k => $_v)
					{
						if ($_v == $this->current_method)
						{
							$methods[] = '[*]'.a(ucfirst(str_replace('_', ' ', $_v)),baseurl($this->current_action.'/'.$_v));
						}
						else 
						{
							$methods[] = a(ucfirst(str_replace('_', ' ', $_v)),baseurl($this->current_action.'/'.$_v));
						}
					}
					$menu['[*]'.a(ucfirst(trim(str_replace('_', ' ', $v))),baseurl($v))] = $methods;
				}
				else 
				{
					$menu[$k] = a(ucfirst(trim(str_replace('_', ' ', $v))),baseurl($v));
				}
			}
			$this->template->menu('default',$menu,true);
			
		}// end function _pre()
		
		/**
		 * Dispatcher
		 * 
		 * Allows the use of subpages via the _GET[subpage]
		 * List your actions in this file.
		 * actions that are preceded with an underscore (_) are hidden.
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function dispatch($params=null)
		{
			// Redirect to the _GET subpage
			if(count($args = func_get_args())>0)
			{
				// Redirect
				$this->template->_r(implode(WS, $args));
			}
			
			// Set the theme name
			$this->theme = $_GET['page'];
			
			// Set the actions folder
			$folder = dirname(__FILE__).DS.'actions';
			
			// Get the files
			$files = array();
			if ( false !== $dir = @opendir( $folder ) ) {
				while (($file = readdir( $dir ) ) !== false ) 
				{
					if ( in_array($file, array('.', '..') ) )
						continue;
					if ( !is_dir( $folder . '/' . $file ) )
					{
						$files[] = $folder . '/' . $file;
					}
				}
			}
			@closedir( $dir );
			
			// Get all available actions
			foreach ($files AS $f)
			{
				$this->actions[] = preg_replace('%^.*?controllers(?>/|\\\\)actions(?>/|\\\\)([^.]*)\..*$%', '$1', $f);
			}

			// Order the files
			sort($this->actions);
			
			// Figure out the current action
			if (isset($_GET['subpage']) && strlen($_GET['subpage']) > 0)
			{
				// Get the elements
				$args = explode('/', $_GET['subpage']);
				
				// Set the current action
				$this->current_action = array_shift($args);
			}
			else 
			{
				// Set the arguments
				$args = array();
				
				// Set the current page
				$this->current_action = isset($this->actions[0])?$this->actions[0]:'_main';
			}
			
			// Set the action
			octoms::$oms_info['controller'] = 'actions'.DS.$this->current_action;
			
			// Does this action exist?
			if (file_exists($f = $folder.DS.$this->current_action.EXT))
			{
				// Load the class
				require_once $f;
				
				// New instance
				$a = new $this->current_action;
				
				// Store this object
				$this->object = $a;
				
				// Bind the libraries
				foreach (octoms::$oms_objects AS $k=>$v)
				{
					$k = substr($k, 0,strpos($k, '_'));
					$a->$k = $v;
				}
				
				// Append the SQL
				$a->sql = $this->sql;
				
				// Get available methods
				foreach (get_class_methods($this->current_action) AS $m) 
				{
					if (0 !== strpos($m, '_'))
					{
						$this->methods[] = $m;
					}
				}
				
				// Get the method
				if (count($args)>0)
				{
					$this->current_method = array_shift($args);
					if ($this->current_method == '') $this->current_method = isset($this->methods[0])?$this->methods[0]:'index';
				}
				else 
				{
					$this->current_method = isset($this->methods[0])?$this->methods[0]:'index';
				}
				
				// Set the method
				octoms::$oms_info['method'] = $this->current_method;
				
				// Does this method exist?
				if (in_array($this->current_method, $this->methods) && method_exists($a, $this->current_method))
				{
					// Preproccessor
					$this->_pre();

					// Store the information
					$a->info = array(
						'current_method'=>$this->current_method,
						'current_action'=>$this->current_action,
						'methods'=>$this->methods,
						'actions'=>$this->actions,
						'theme'=>$this->theme
					);
					
					// Set the parameters
					octoms::$oms_info['parameters'] = $args;
					
					// Call it
					call_user_func_array(array($a,$this->current_method), $args);
					
					// Postproccessor
					$this->_post();
				}
				elseif ($this->current_method == 'index')
				{
					// The index method is mandatory!
					trigger_error('Please define the index method in "'.$f.'"');
				}
				else 
				{
					// Set the warning
					$this->session->flash_set('error','Bad page');
					
					// Redirect to the front page with a warning
					header('Location:'.ADMINROOT.'?page='.$this->theme);exit();
				}
			}
			else 
			{
				// The file must be created
				trigger_error('Please create the "'.$f.'" controller.');
			}
		}// end function dispatch()
		
		/**
		 * Postproccessor
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function _post()
		{
			// Listen for the keyword #*# for the AJAX interface
			if ($this->input->post('#*#'))
			{
				// Prepare the API response array
				$api = array();
				
				// Set the status
				is_null($api['_status_'] = $this->template->_get1('api_status'))?($api['_status_'] = array('Done.',true)):null;
				
				// Set the filters
				$api['_filters_'] =(is_null($api['_filters_'] = $this->template->_get1('api_filters')))?array():array_flat($api['_filters_']);
				
				// Set the content
				!is_null($cnt = $this->template->_get1('api_content'))?($api['_content_']=$cnt):null;
				
				// This is a plain JSON response
				$this->template->_conf('whitescreen',true);
				while(@ob_end_clean());
				
				// We <3 JSON
				print json_encode($api);
				exit();
			}

			// Non Ajax page response
			if (isset($_SESSION['__flash__']['api_status']))
			{
				// Get the information
				$status = $this->session->flash_get('api_status');
				$filters = $this->session->flash_get('api_filters');
				$content = $this->session->flash_get('api_content');
				
				// Prepare the data
				$data = array();
				if (null!=$status) $data['_status_'] = $status;
				if (null!=$filters) $data['_filters_'] = $filters;
				if (null!=$content) $data['_content_'] = $content; 
				
				// Print the javascript
				print js(str_replace(array("\n","\t"), '',
					'jQuery(document).ready(function(){
						window.setTimeout(function(){
							wp_octoms.yform('.json_encode($data).');
						},200);
					});'),
					false
				);
			}
			
			// Flush the data
			$this->template->_flush();
			
		}// end function _post()
		
	}// end class lighthouse
	
	
/* End Of File <lighthouse.inc> */